package edu.mercer.sse.app;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;
import java.util.logging.Level;

import com.google.common.base.Optional;

/**
 * 
 * Load settings / properties from application xml / ini file.<p>
 *
 * Default values supplied for constants with overrides permitted from ini 
 * 	file.<p> 
 *
 */

public class Config
{
	private static final Path CONFIG_XML = Paths.get( "config.xml" );
	
	private static Optional<Properties> _config = Optional.absent();
	
	
	private Config()
	{
		super();
		
	}//constructor

	
	public static Properties settings()
	{
		if( ! _config.isPresent() ) _config = loadProperties();
		
		return _config.get();
		
	}//method
	
	
	public static Level getLogLevel()
	{
		return Level.parse(Config.settings()
				  	.getProperty("log-level")
				  	.toUpperCase());
		
	}//method
	
	
	private static Optional<Properties> loadProperties()	
	{
		final Properties prop = new Properties();

		try
		{
			prop.loadFromXML( Files.newInputStream(CONFIG_XML, 
							  StandardOpenOption.READ) );
			
		}
		catch( final InvalidPropertiesFormatException err )
		{
			App.abend( "XML configuration file: " + CONFIG_XML + " corrupted", 
					err );
		}
		catch( final IOException err )
		{
			App.abend( "XML configuration file: " + CONFIG_XML + " IO error", 
					err );
			
		}//try

		//remove whitespace from xml
		
		for( Integer ct=0; ct<prop.size(); ct++ )
		{
			prop.setProperty( (String) prop.keySet().toArray()[ct], 
					((String) prop.values().toArray()[ct]).trim() );
			
		}//for
		
		return Optional.of( prop );
		
	}//method
	

}//class
